<template>
  <base-layout
    :dialog-title="dialogTitle"
    :dialog-visible="dialogVisible"
    dialog-width="600px"
    :page-show="pageShow"
    @dialog-close="dialogClose"
  >
    <template #toolPanel >
      <el-dialog title="分销商充扣值" size="tiny" width="30%" :visible.sync="rechargeFormVisible" :close-on-click-modal="false">
        <el-form :model="rechargeForm" label-width="110px" ref="rechargeForm">

          <el-form-item label="剩余金额" prop="downshopbalance">
            <el-input v-model="rechargeForm.downshopbalance" :disabled="true"></el-input>
          </el-form-item>
          <el-form-item label="充扣值选项">
            <el-radio-group v-model="rechargeForm.recharge">
              <el-radio :label="1">充值</el-radio>
              <el-radio :label="0">扣款</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="充扣值金额" prop="rechargeamount" :rules="[
				  { required: true, message: '不能为空'},
				  { type: 'number', message: '金额必须为数字值'}
				]">
            <el-input type="rechargeamount" v-model.number="rechargeForm.rechargeamount" auto-complete="off"
                      @input="rechargeamountchange"></el-input>
          </el-form-item>
          <el-form-item label="总金额" prop="sumamount">
            <el-input type="text" v-model="rechargeForm.sumamount" disabled="disabled"></el-input>
          </el-form-item>
          <el-form-item label="备注">
            <el-input type="textarea" v-model="rechargeForm.remark"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer" style="text-align: center;">
          <el-button size="small" round @click.native="rechargeFormVisible = false">取消</el-button>
          <el-button type="primary" size="small" round @click.native="rechargeSubmit" >提交</el-button>
        </div>
      </el-dialog>
    </template>
    <template #searchPanel>
      <search-panel :show-add-button="isCompetence" :showbatchHandleOpen="isCompetence" :showbatchHandleClose="isCompetence"
                    @batchHandleOpen="batchHandleOpen" @batchHandleClose="batchHandleClose" :showSendButton="false"
                    :show-search-button="isCompetence" @insert="handleDataInsert" @search="search" :left="true">
        <el-form-item label="分销名称:" v-show="isCompetence" >
          <el-input v-model="filters.name"  clearable placeholder="分销商名称"></el-input>
        </el-form-item>
        <el-form-item label="商家账号:" v-show="isCompetence" >
          <el-input v-model="filters.phonenum" clearable placeholder="商家账号"></el-input>
        </el-form-item>
        <el-form-item label="状态:"  v-show="isCompetence">
          <el-select v-model="filters.userstatus" clearable placeholder="请选择状态">
            <el-option value="0" label="全部">全部</el-option>
            <el-option value="1" label="正常">正常</el-option>
            <el-option value="3" label="关闭">关闭</el-option>
            <el-option value="2" label="维护">维护</el-option>
          </el-select>
        </el-form-item>
      </search-panel>
    </template>
    <template #contentPanel>
      <data-table
        :value="tableData"
        :total-count="totalCount"
        :has-action="isCompetence"
        :current="start"
        :width="425"
        :table-column-attributes="tableColumnAttributes"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :isShowSelection="true"
        @selection-change="selsChange"
      >
        <template #action="{row}">
          <el-button size="small" round @click="handleEnable(row)">{{row.user.userstatus == '2' ? '渠道启用' : '渠道维护'}}</el-button>
          <el-button size="small" round @click="handleEnableIsOpen(row)">{{row.user.userstatus == '1' || row.user.userstatus == '2'? '渠道关闭' : '渠道开启'}}</el-button>
          <el-button size="small" round @click="handleEdit(row)">编辑</el-button>
          <el-button size="small" round @click="updateKey(row)">更新密匙</el-button>
          <el-button size="small" round @click="rechargeEdit(row)">充扣值</el-button>
        </template>
      </data-table>
    </template>

    <template #dialog>
        <el-form :model="form" label-width="100px" ref="form">
          <el-form-item label="省份" prop="provinceuuid">
            <el-select v-model="form.provinceuuid" placeholder="请选择省份" class="usernamewidth" filterable
                       style="width: 335px;">
              <el-option
                v-for="item in options"
                :key="item.provinceuuid"
                :label="item.provincename"
                :value="item.provinceuuid">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="分销商名称" prop="username">
            <el-input v-model="form.username" class="usernamewidth" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item label="公司名称" >
            <el-input v-model="form.wechatid" class="usernamewidth" auto-complete="off"></el-input>
          </el-form-item>
          <!--<el-form-item label="商家编号" prop="downshopnum">-->
          <!--<el-input v-model="form.downshopnum" auto-complete="off"></el-input>-->
          <!--</el-form-item>-->
          <el-form-item label="商家账号" prop="phonenum">
            <el-input v-model="form.phonenum" class="usernamewidth" auto-complete="off" placeholder="登录账号"></el-input>
          </el-form-item>
          <el-form-item label="渠道API" prop="downshopnum">
            <el-select v-model="form.downshopnum" placeholder="请选择下游渠道API" class="usernamewidth" collapse-tags filterable
                       style="width: 335px;">
              <el-option
                v-for="item in downoptions"
                :key="item.downshopnum"
                :label="item.downshopnumName"
                :value="item.downshopnum">
              </el-option>
            </el-select>
            <!--                    <el-input v-model="form.downshopnum" auto-complete="off"></el-input>-->
          </el-form-item>
          <el-form-item label="登录密码" prop="password">
            <el-input v-model="form.password" class="usernamewidth" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item label="授信额度" prop="credit">
            <el-input v-model="form.credit" class="usernamewidth" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item label="提醒金额">
            <el-input v-model="form.noticeBalance" class="usernamewidth" placeholder="余额少于多少发送提示消息" ></el-input>
          </el-form-item>
          <el-form-item label="分销商IP" prop="downshopip">
            <el-input v-model="form.downshopip" class="usernamewidth" auto-complete="off" placeholder="多个以,分割,如127.0.0.1,111.1.1.1"></el-input>
          </el-form-item>
          <el-form-item label="回调地址" prop="orderCallAddress" >
            <el-input v-model="form.orderCallAddress" class="usernamewidth" auto-complete="off" placeholder="回调地址"></el-input>
          </el-form-item>
          <el-form-item label="备注">
            <el-input type="textarea" class="usernamewidth" v-model="form.remark"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer el-dialog__footer">
          <el-button size="small" round @click.native="dialogVisible = false">取消</el-button>
          <el-button size="small" round  type="primary" @click.native="addSubmit">提交</el-button>
        </div>
    </template>

  </base-layout>
</template>

<script>
import baseMixin from '@/mixins/base'

import {findDownShopPage,noticeDownSwitch,handleEnableShop,handleEnableShopIsOpen,updateDownShopKey,downRecharge,findOneDownShop,
  addDownShop,updateDownShop} from '@/api/downapi'
import { findAllPro } from '@/api/utilsapi'
import util from "../../utils/util";
var crypto = require('crypto');

export default {
  name: 'UserManager',
  components: {  },
  mixins: [
    baseMixin({
      idName: 'id',
      refresh: '',
      findData:findDownShopPage,
      format(res) {
        return res.map(data => {
          return data
        })
      }
    })
  ],
  data() {
    return {
      buttons: [],
      options:[],
      pageShow: true,
      dialogData:{},
      isShowKey: util.checkRoleAdminAndSuper() ? true : false,
      isCompetence: util.checkRoleAdminAndSuper() ? true : false,
      sels:[],
      downoptions:[{downshopnum:'jingheng',downshopnumName:'敬恒'},{downshopnum:'defaultApi',downshopnumName:'默认'},
        {downshopnum:'yisai',downshopnumName:'易赛'}],
      tableColumnAttributes: [
        { name: '分销商ID', value: 'useruuid' , formatter : this.useruuiFormatter , width:265},
        { name: '分销商名称', value: 'username', formatter : this.userNameFormatter , width:120 },
        { name: '渠道状态', value: 'userstatus' , formatter : this.userstatusFormatter },
        { name: '渠道API', value: 'downshopnum' },
        { name: '商家账号', value: 'phonenum' , formatter : this.phonenumFormatter},
        { name: '商户余额', value: 'downshopbalance', width:110 },
        { name: '累计加款', value: 'totalMoney', width:110 },
        { name: '授信额度', value: 'credit' , width:90},
        { name: '通知金额', value: 'noticeBalance' , width:90, isCompetence: util.checkRoleAdminAndSuper()},
        { name: '余额通知', value: 'noticeSwitch', type:'switchoff' , changeFunc : this.noticeSwitchSwitch, isCompetence: util.checkRoleAdminAndSuper()},
        { name: '分销商IP', value: 'downshopip' },
        { name: '分销商密匙', value: 'downkey' , width:265 , isCompetence: util.checkRoleAdminAndSuper()},
        { name: '创建时间', value: 'createtime' , width:150},
        { name: '备注', value: 'remark' , formatter : this.remarkFormatter , width:200}
      ],
      filters: {
        name: '',
        userstatus:'',
        phonenum:'',
        useruuid:''
      },
      rechargeForm:{
        downshopbalance: 0,
        rechargeamount: 0,
        sumamount: '',
        downshopuuid: '',
        remark: '',
        recharge: 1
      },
      rechargeFormVisible: false,
      form : {
        username: '',
        downshopnum: '',
        phonenum: '',
        downshopip: '',
        remark: '',
        password: '',
        usertype: '3',
        downshopbalance: '',
        provinceuuid: '',
        merchantcredit: 0,
        credit:'0.00',
        orderCallAddress:'',
        wechatid:'',
        noticeBalance:0
      },
    }
  },
  methods: {
    async search(form){
      let para = {
        shopName: this.filters.shopName,
        start: 0,
        pageSize: 10,
        shopName: this.filters.name,
        useruuid: this.$store.getters.useruuid,
        userstatus: this.filters.userstatus == 0 ? "" : this.filters.userstatus,
        phonenum: this.filters.phonenum,
      };
      this.searchOptions = para;
      this.setTableData()
    },
    handleEdit(row){
      let para = {useruuid: row.user.useruuid};
      findOneDownShop(para).then(datas => {
        let {message, code, data} = datas;
        if (code !== "0") {
          this.showMsg(message,"error");
        } else {
          this.form.username = data.user.username;
          this.form.downshopnum = data.downshopnum;
          this.form.phonenum = data.user.phonenum;
          this.form.downshopip = data.downshopip;
          this.form.remark = data.user.remark;
          this.form.provinceuuid = data.provincialInformation.provinceuuid;
          this.form.useruuid = data.user.useruuid;
          this.form.credit = data.credit;
          this.form.orderCallAddress = data.orderCallAddress;
          this.form.wechatid = data.user.wechatid;
          this.form.noticeBalance = data.noticeBalance;
          this.dialogTitle = "编辑";
          this.dialogVisible = true;
        }
      });
    },
    updateKey(row){
      this.$confirm('确认更新密匙吗?', '提示', {
        type: 'warning',
        roundButton:true
      }).then(() => {
        let para = {useruuid: row.user.useruuid};
        updateDownShopKey(para).then(datas => {
          this.resultSuccess(datas);
        });
      }).catch(() => {
      });
    },
    userNameFormatter(row){
      return row.user.username;
    },
    useruuiFormatter(row){
      return row.user.useruuid;
    },
    userstatusFormatter(row){
      return row.user.userstatus === 1 ? '渠道正常' : row.user.userstatus === 2 ? '渠道维护' : row.user.userstatus === 3 ? '渠道关闭' :"其他";
    },
    phonenumFormatter(row){
      return row.user.phonenum;
    },
    remarkFormatter(row){
      return row.user.remark;
    },
    noticeSwitchSwitch(row){
      noticeDownSwitch(row).then((datas) => {
         this.resultSuccess(datas);
      });
    },
    handleEnable(row) {
      this.$confirm('确认维护or启用该商家状态吗?', '提示', {
        type: 'warning',
        roundButton:true
      }).then(() => {
        let para = {
          userstatus: row.user.userstatus == "2" ? "1" : "2",
          useruuid: row.user.useruuid
        };
        handleEnableShop(para).then((res) => {
          this.resultSuccess(res);
        });
      });
    },
    handleEnableIsOpen(row) {
      this.$confirm('确认关闭or启用该商家状态吗?', '提示', {
        type: 'warning',
        roundButton:true
      }).then(() => {
        let para = {
          userstatus: row.user.userstatus == "3" ? "1" : "3",
          useruuid: row.user.useruuid
        };
        handleEnableShop(para).then((res) => {
          this.resultSuccess(res);
        });
      }).catch(() => {
      });
    },
    batchHandleOpen(){
      this.batachShops("open");
    },
    batchHandleClose(){
      this.batachShops("close");
    },
    batachShops(type){
      if(this.sels.length == 0){
        this.$message({
          message: "请选择渠道",
          type: 'error'
        });
        return;
      }
      this.$confirm('确认批量关闭or启用该商家状态吗?', '提示', {
        type: 'warning',
        roundButton:true
      }).then(async () => {
        let results;
        for(var i = 0 ; i < this.sels.length ; i++){
          let para = {
            userstatus: type == "open" ? "1" : "3",
            useruuid: this.sels[i].user.useruuid
          };
          const result = await handleEnableShop(para);
          results = result;
        }
        this.resultSuccess(results);
      }).catch((e) => {
        console.log(e)
      });
    },
    selsChange: function (sels) {
      this.sels = sels;
    },
    rechargeEdit(row) {
      this.rechargeFormVisible = true;
      this.rechargeForm.downshopbalance = row.downshopbalance;
      this.rechargeForm.downshopuuid = row.downshopuuid;
      this.rechargeForm.rechargeamount = 0;

    },
    rechargeamountchange() {
      try {
        var reg = new RegExp("^([0-9]|[.][0-9])*$");
        if (reg.test(this.rechargeForm.rechargeamount)) {
          if (this.rechargeForm.recharge == 1) {
            this.rechargeForm.sumamount = this.numAdd(this.rechargeForm.downshopbalance, this.rechargeForm.rechargeamount);
          } else {
            this.rechargeForm.sumamount = this.numSubtraction(this.rechargeForm.downshopbalance, this.rechargeForm.rechargeamount);
          }
        } else {
          this.rechargeForm.rechargeamount = "";
        }
      } catch (e) {
        console.log(e);
      }
    },
    //充值
    rechargeSubmit () {
      this.$refs.rechargeForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {roundButton:true}).then(() => {
            let para = {
              remark: this.rechargeForm.remark,
              downshopuuid: this.rechargeForm.downshopuuid,
              downshopbalance: this.rechargeForm.rechargeamount,
              recharge: this.rechargeForm.recharge
            };
            downRecharge(para).then((datas) => {
              this.resultSuccess(datas);
              this.rechargeFormVisible = false;
            });
          });
        }
      });
    },
    findAllPro(){
      let para = {
        test:''
      };
      findAllPro(para).then(datas => {
        let {message, code, data} = datas;
        if (code !== "0") {
          this.showMsg(message,"error");
        } else {
          this.options = data;
        }
      });
    },
    addSubmit(){
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {roundButton:true}).then(() => {
            let para = Object.assign({}, this.form);
            para.usertype = '3';
            if(!this.form.useruuid){
              para.credit = "0.00";
              var md5 = crypto.createHash('md5');
              para.password = md5.update(para.password).digest('hex');
              addDownShop(para).then((datas) => {
                this.resultApply(datas)
              });
            }else{
              updateDownShop(para).then((datas) => {
                this.resultApply(datas)
              });;
            }
          });
        }
      });
    }
  },
  mounted() {
    this.findAllPro();
  }
}
</script>
<style scoped>
  .usernamewidth{
    width: 334px;
  }
  .el-dialog__footer{
    text-align: center;
  }
</style>
